<template>
  <div class="flex flex-col">
    <div class="flex justify-between items-center mb-[20px]">
      <div class="title">{{ t("formula_detail.material_ratio") }}</div>
      <div class="flex items-center">
        <el-button type="primary" @click="multipleSet"
          >{{ t("formula_detail.batch_set_amount") }}
        </el-button>
      </div>
    </div>
    <div class="h-[calc(100vh_-_275px)] material-table">
      <!--      <AuTable ref="tableRef" v-bind="gridOption">-->
      <!--        &lt;!&ndash;        <template v-for="item in slotList" :key="item" v-slot:[item]="{ row }">&ndash;&gt;-->
      <!--        &lt;!&ndash;          <el-input-number v-model="row.amount" :min="0" />&ndash;&gt;-->
      <!--        &lt;!&ndash;        </template>&ndash;&gt;-->
      <!--        <template v-slot:106_default="{ row }">-->
      <!--          {{ slotList }}-->
      <!--          <el-input-number v-model="row.amount" :min="0" />-->
      <!--        </template>-->
      <!--      </AuTable>-->
      <vxe-table
        stripe
        height="auto"
        border="none"
        show-overflow
        :data="gridOption.dataSource"
      >
        <vxe-column
          v-for="item in gridOption.columns"
          :key="item.field"
          :field="item.field"
          :title="te(item.title) ? t(item.title) : item.title"
          :width="item.width"
        >
          <template v-if="item.field !== 'materialSpecs'" v-slot="{ row }">
            <vxe-input
              v-model="row[item.field]"
              class="mat-num-input"
              :placeholder="t('formula_detail.positive_number')"
              type="number"
              min="0"
              clearable
            />
          </template>
        </vxe-column>
      </vxe-table>
    </div>

    <AuFormModal
      ref="formModalRef"
      v-model="showModal"
      :title="t(title)"
      :formList="formList"
      :modalProps="{
        width: 500
      }"
      :formProps="{
        class: '!w-[386px]',
        labelWidth: '130px'
      }"
      @handleConfirm="handleConfirm"
    />
  </div>
</template>

<script setup lang="ts">
import { AuTable } from "@/components/AuTable";
import { getCurrentInstance, reactive, ref, watch } from "vue";
import { PropDefines } from "@/components/AuTable/type";
import { MaterialProp } from "@/api/cabinet/material";
import { AuFormModal } from "@/components/AuModal";
import { cloneDeep } from "lodash-unified";
import { RegInt } from "@/utils/tool";
import { useI18n } from "vue-i18n";

const props = defineProps<{
  materialRatioData: any[];
}>();

const { t, te } = useI18n();

const gridOption = reactive<PropDefines>({
  isServerPage: false,
  showIndex: false,
  columns: [
    {
      field: "materialSpecs",
      title: "formula_detail.material_type",
      width: 200
    }
  ],
  actions: [],
  topTools: [],
  operateTools: [],
  dataSource: [],
  vxeTableConfig: {
    pagerConfig: {
      enabled: false
    }
  }
});
const slotList = ref([]);
const { proxy } = getCurrentInstance();

const showModal = ref(false);
const title = ref("formula_detail.batch_set_amount");
const formList = ref<any[]>([]);

let materialList = [];

const multipleSet = () => {
  if (!gridOption.dataSource.length) {
    proxy.$auMessageBox.alert(t("formula_detail.no_match_material_data"));
    return;
  }
  showModal.value = true;
};

const handleConfirm = (data: any) => {
  gridOption.dataSource = gridOption.dataSource.map(item => {
    return {
      ...item,
      ...data
    };
  });
  showModal.value = false;
};

type MaterialAmountType = {
  amount: string;
  material_id: number;
  material_name: string;
  amount_unit: string;
};

interface MaterialRatioData {
  edit_status: number;
  materialAmount: MaterialAmountType[];
  materialSpecs: {
    specification_id: number;
    attr: string;
  }[];
}

function isSpecMatch(spec1, spec2) {
  // 将两个规格字符串按"-"分割成数组
  const features1 = spec1.split("-");
  const features2 = spec2.split("-");

  // 数量不同直接返回不匹配
  if (features1.length !== features2.length) {
    return false;
  }

  // 对特性数组进行排序
  const sortedFeatures1 = [...features1].sort();
  const sortedFeatures2 = [...features2].sort();

  // 检查排序后的数组是否完全一致
  return sortedFeatures1.every(
    (feature, index) => feature === sortedFeatures2[index]
  );
}

function getUniqueMaterialAmounts(data: MaterialRatioData[]) {
  const seen = new Set(); // 记录已存在的唯一标识
  const result = []; // 存储最终结果

  // 遍历每个对象
  data.forEach(group => {
    // 遍历每个 materialAmount
    group.materialAmount.forEach(item => {
      // 生成唯一标识（组合关键字段）
      const uid = `${item.material_id}-${item.material_name}`;

      // 如果不存在则加入结果
      if (!seen.has(uid)) {
        seen.add(uid);
        result.push({
          material_id: item.material_id,
          material_name: item.material_name,
          amount: {},
          amount_unit: item.amount_unit
        });
      }
    });
  });

  return result;
}

const setTableData = (list: MaterialRatioData[]) => {
  if (list.length) {
    materialList = getUniqueMaterialAmounts(list);
    slotList.value = [];
    formList.value = [];
    gridOption.columns = [
      {
        field: "materialSpecs",
        title: "formula_detail.material_type1",
        width: 200
      },
      ...materialList.map(item => {
        slotList.value.push(`${item.material_id}_default`);
        formList.value.push({
          type: "vxe-input",
          label: `${item.material_name}（${item.amount_unit}）`,
          key: String(item.material_id),
          inType: "number",
          min: 0
        });
        return {
          field: String(item.material_id),
          title: `${item.material_name}（${item.amount_unit}）`,
          slots: {
            default: `${item.material_id}_default`
          }
        };
      })
    ];

    gridOption.dataSource = list.map((item, i) => {
      const data = {
        materialSpecs: item.materialSpecs.map(v => v.attr).join("-")
      };
      const find = gridOption.dataSource.find(h =>
        isSpecMatch(h.materialSpecs, data.materialSpecs)
      );
      // console.log(item, find);
      materialList.forEach(v => {
        data[String(v.material_id)] = find
          ? find[String(v.material_id)]
          : item.materialAmount.find(h => h.material_id === v.material_id)
              ?.amount;
      });
      console.log(data);
      return data;
    });
    // gridOption.dataSource = list.map(item => {
    //   const data = {
    //     materialSpecs: item.materialSpecs.map(v => v.attr).join("-")
    //   };
    //   materialList.forEach(v => {
    //     data[String(v.material_id)] = v.amount;
    //   });
    //   return data;
    // });
  }
};

const getAmountData = () => {
  const list = cloneDeep(props.materialRatioData);
  const amountData = list.map((item, i) => {
    const gridItem = gridOption.dataSource[i];
    return {
      ...item,
      materialAmount: item.materialAmount.map(v => {
        return {
          ...v,
          amount: gridItem[String(v.material_id)]
        };
      })
    };
  });
  console.log(amountData);
  return amountData;
};

const handleInput = (key: string, row: any, val: string) => {
  row[key] = val.replace(/[^0-9]/g, "");
};

const setRatioData = (data: any) => {};

const validate = () => {
  const list = gridOption.dataSource;
  const matIds = materialList.map(v => v.material_id);
  let isAllEmpty = true,
    firstErrMsg = "",
    validFirst = 0;
  for (let i = 0; i < list.length; i++) {
    const item = list[i];
    for (const matId of matIds) {
      if (!item[String(matId)] && validFirst === 0) {
        firstErrMsg = t("formula_detail.material_amount_empty", {
          row: i + 1,
          specs: item.materialSpecs,
          id: matId
        });
        validFirst++;
      }
      if (item[String(matId)]) {
        isAllEmpty = false;
      }
    }
  }

  if (!isAllEmpty && validFirst !== 0) {
    proxy.$auMessageBox.alert(firstErrMsg, t("notice.title"));
    return false;
  }
  return true;
};

defineExpose({
  getAmountData,
  setRatioData,
  validate
});

watch(
  () => props.materialRatioData,
  val => {
    setTableData(val);
  }
);
</script>

<style scoped lang="scss">
.mat-num-input {
  :deep(.vxe-input--control-icon) {
    display: none;
  }
}
</style>
